﻿using System.Collections;
using System.Threading.Tasks;
using System.IO;
using UnityGameFramework.Runtime;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
using Utility = GameFramework.Utility;

namespace StarForce
{
    public class WebImageComponents : GameFrameworkComponent
    {
        // private string[] m_imageUrl = new string[]
        // {
        //     "http://t8.baidu.com/it/u=2247852322,986532796&fm=79&app=86&f=JPEG?w=1280&h=853",
        //     "http://t9.baidu.com/it/u=3363001160,1163944807&fm=79&app=86&f=JPEG?w=1280&h=830",
        //     "http://t9.baidu.com/it/u=583874135,70653437&fm=79&app=86&f=JPEG?w=3607&h=2408",
        //     "http://t9.baidu.com/it/u=2268908537,2815455140&fm=79&app=86&f=JPEG?w=1280&h=719",
        //     "http://t7.baidu.com/it/u=1179872664,290201490&fm=79&app=86&f=JPEG?w=1280&h=854",
        //     "http://t9.baidu.com/it/u=3923875871,1613462878&fm=79&app=86&f=JPEG?w=1280&h=854",
        //     "http://t9.baidu.com/it/u=3949188917,63856583&fm=79&app=86&f=JPEG?w=1280&h=875",
        //     "http://t7.baidu.com/it/u=1355385882,1155324943&fm=79&app=86&f=JPEG?w=1280&h=854",
        //     "http://t8.baidu.com/it/u=2857883419,1187496708&fm=79&app=86&f=JPEG?w=1280&h=763",
        //     "http://t7.baidu.com/it/u=830740827,3648735644&fm=79&app=86&f=JPEG?w=1280&h=853",
        //     "http://t8.baidu.com/it/u=198337120,441348595&fm=79&app=86&f=JPEG?w=1280&h=732",
        //     "http://t9.baidu.com/it/u=1577456063,1344044640&fm=79&app=86&f=JPEG?w=1280&h=853",
        //     "http://t8.baidu.com/it/u=2678662753,1297312162&fm=79&app=86&f=JPEG?w=1181&h=787",
        //     "http://t9.baidu.com/it/u=1373840141,993565751&fm=79&app=86&f=JPEG?w=1181&h=788"
        // };

        void Start()
        {
            // 有没有ImageCache文件夹 没有的创建一个 
            if (!Directory.Exists(Application.persistentDataPath+"/ImageCache/"))
            {
                Directory.CreateDirectory(Application.persistentDataPath + "/ImageCache/");
            }
        }

        public async void SetAsyncImage(string url,RawImage rawImage)
        {
            string path = Utility.Text.Format("{0}{1}{2}", Application.persistentDataPath, "/ImageCache/", url.GetHashCode());
            // 判断是否第一次加载图片
            if (!File.Exists(path))
            {
                rawImage.texture = await GetRemoteTexture(url);
            }
            else
            {
                StartCoroutine(DownloadImage(url, rawImage));
            }
        }

        IEnumerator DownloadImage(string url, RawImage rawImage)
        {
            //Log.Info("本地路径:{0}",Utility.Text.Format("{0}{1}{2}",Application.persistentDataPath,"/ImageCache/",url.GetHashCode()));
            string filepath = Utility.Text.Format("{0}{1}{2}",Application.persistentDataPath,"/ImageCache/",url.GetHashCode());
            WWW www = new WWW("file:///"+filepath);

            yield return www;

            rawImage.texture = www.texture;
        }

        public static async Task<Texture2D> GetRemoteTexture(string url)
        {
            using (UnityWebRequest www = UnityWebRequestTexture.GetTexture(url))
            {
                var asyncOp = www.SendWebRequest();

                while (asyncOp.isDone == false)
                {
                    await Task.Delay(1000 / 30);
                }

                if (www.isNetworkError || www.isHttpError)
                {
                    // log error:
#if DEBUG
                    Log.Error($"{www.error}, URL:{www.url}");
#endif
                    // nothing to return on error:
                    return null;
                }
                else
                {
                    //Log.Info("加载图片完毕 : {0}", Application.persistentDataPath);
                    byte[] pngData = DownloadHandlerTexture.GetContent(www).EncodeToJPG();
                    
                    File.WriteAllBytes(Utility.Text.Format("{0}{1}{2}",Application.persistentDataPath,"/ImageCache/",url.GetHashCode()), pngData);
                    // return valid results:
                    return DownloadHandlerTexture.GetContent(www);
                }
            }
        }
    }
}